<?php if(!defined('PUBLIC_DIR')) die('No Access!');
using('System');
using('System.Data');
using('System.Web.MVC');

Cnamespace('System.Web.MVC');
class Router implements iRouter{
	private static $DBHandler = null;
	private $Request;
	private $Routes;
	private $MatchedRoutes;

	public function __construct(Request $_request){
		$this->Request = $_request;
		if (self::$DBHandler == NULL)
			self::$DBHandler = Config::GetProvider();
		self::$DBHandler->Query("SELECT * FROM [Routes];");
		$routes = self::$DBHandler->FetchArray();
		foreach($routes as $route){
			$params = array();
			if(is_array(unserialize($route['additionalParameters'])))
				$params = unserialize($route['additionalParameters']);
			if(is_string($route['name']) && $route['name'] != '')
				$this->Routes[] = new Route($route['name'], new Uri($route['name'], $route['pattern'], (array)unserialize($route['conditions'])), new Action($route['action']), $params);
		}
	}
	public function RegisterEvents(){
		if(is_array($this->Routes))
			foreach($this->Routes as $route){
				if($route->Match($this->Request->Referer()))
					$this->MatchedRoutes[] = $route;
			}
		if(isset($this->MatchedRoutes[0]))
			Dispather::Invoke($this->MatchedRoutes[0]->getAction(), $this->MatchedRoutes[0]->getParams());
		else
			trigger_error("404 Not found");
	}
	public function Routing(){
		foreach($this->Routes as $route){
			if($route->Match($this->Request->Referer()))
				$this->MatchedRoutes[] = $route;
		}
		if(isset($this->MatchedRoutes[0]))
			Dispather::Invoke($this->MatchedRoutes[0]->getAction(), $this->MatchedRoutes[0]->getParams());
	}
}
